package com.fuyao.cloud.admin.flow.actor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fuyao.cloud.flowable.entity.ActorUser;
import com.fuyao.cloud.admin.api.entity.SysDept;
import com.fuyao.cloud.admin.api.entity.SysUser;
import com.fuyao.cloud.flowable.vo.ActorInstance;
import com.fuyao.cloud.admin.service.SysDeptService;
import com.fuyao.cloud.admin.service.SysUserService;
import com.fuyao.cloud.common.security.service.CloudUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 定义部门-规则，用于获取指定一个或多个部门下的用户
 * 例：指定部门编码 BM0001;BM0002 则会加载这两个部门的用户信息。
 * 注：使用分号;隔开对应的部门编码
 *
 * @author lyhill
 * @version 1.0
 * @date 2022年11月18日
 */
@Slf4j
@ActorTypeCodeAnnotation("AT_DEPT")
@Component
public class ActorTypeAtDept implements ActorTypeFactory {

    @Autowired
    public SysUserService userService;

    @Autowired
    private SysDeptService deptService;

    @Override
    public List<ActorInstance> execute(CloudUser user, ActorUser actorUser, String procInstId) {
        log.info("AT_DEPT : actorId:{}, procInstId:{}", actorUser.getActorId(), procInstId);

        if (ObjectUtil.isEmpty(actorUser) || StrUtil.isEmpty(actorUser.getParams())) {
            return Lists.newArrayList();
        }
        // 根据配置的部门-编码查询部门的信息。
        String params = actorUser.getParams();
        List<SysDept> deptList = deptService.listByDeptCode(StrUtil.split(params, ';'));

        if (CollUtil.isEmpty(deptList)) {
            return Lists.newArrayList();
        }

        List<Long> deptIds = deptList.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        List<ActorInstance> actorInstanceList = Lists.newArrayList();
        List<SysUser> userList = userService.listByDeptIds(deptIds);
        userList.forEach(sysUser -> {
            ActorInstance actorInstance = new ActorInstance(sysUser);
            actorInstanceList.add(actorInstance);
        });
        return actorInstanceList;
    }
}
